#!/bin/python3
# -*- coding: UTF-8
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.colors
import matplotlib.dates as mdates
from matplotlib.ticker import ScalarFormatter
from matplotlib.ticker import LogFormatter
from matplotlib.ticker import MultipleLocator
from matplotlib.ticker import FormatStrFormatter
from matplotlib.font_manager import findfont, FontProperties  
import matplotlib.font_manager as font_manager
import seaborn as sns
# sns.set_theme()

sns.set_theme(style="ticks", font_scale=1.33)
sns.set_context("paper", font_scale=1.5)
plt.rcParams['xtick.direction'] = 'in'#将x的刻度线方向设置向内
plt.rcParams['ytick.direction'] = 'in'#将y的刻度方向设置向内
plt.rcParams['font.family']=['Sarasa Mono SC'] #用来正常显示中文标签
txt_thread_nr = "线程数"
txt_mops = "异步/同步接口加速比"

# plt.rcParams['axes.xmargin'] = 0

# 常量颜色
cl_blk = (7/255,7/255,7/255,1)
cl_red = (255/255,59/255,59/255,1)
cl_orange = (255/255,160/255,122/255, 1)

use_abench = 'bench_async'
use_bbench = 'bench_sync'

markers=[
	# ".", #atm_add
	".", #posix
	"d", #pspin
	"x", #spin
	"s", #ticket
	"v", #clh
	"^", #mcs
	"o", #flat
	"v", #ccsynch
	"^", #dsmsynch
	"+", #hsynch
	">", #sffwd
	]
colors=[
	cl_blk, #posix
	cl_blk, #pspin
	cl_blk, #spin
	cl_blk, #ticket
	cl_blk, #clh
	cl_blk, #mcs
	cl_blk, #flat
	cl_blk, #ccsynch
	cl_blk, #dsmsynch
	cl_blk, #hsynch
	cl_blk, #sffwd

	# cl_blk, #fc
	# cl_blk, #ccsynch
	# cl_blk, #dsmsynch
	# cl_blk, #hsynch
	# cl_blk, #rcl
	# cl_orange, #sffwd
	# cl_red, #cacfc
	# cl_red, #cacccsynch
	# cl_red, #cacdsmsynch
	# cl_red, #cachsynch
]

fst=[
	"none", #posix
	"none", #pspin
	"none", #spin
	"none", #ticket
	"none", #clh
	"none", #mcs
	"none", #flat
	"none", #ccsynch
	"none", #dsmsynch
	"none", #hsynch
	"none", #sffwd
]

from scipy.stats.mstats import gmean
import sys
import common

def avg(data):
	# 获得所有lib名字(除去第一行)
	libname = common.uniqx(data[1:])
	# 获得所有bench 名字
	benchname = common.uniqx(common.filter(data, libname[0]))
	# 获得所有的thread
	threadlist = common.uniqx(common.filter(common.filter(data, libname[0]), benchname[0])).astype(int)
	threadlist.sort()
	threadlist = threadlist.astype(str)

	# 计算n次执行结果的平均值和标准差
	avg_result = []
	for lib in libname:
		for bench in benchname:
			for thread in threadlist:
				# 多次执行结果 计算平均值和标准差
				result_data = common.filter(common.filter(common.filter(data, lib), bench), thread).astype(float)
				avg_result.append(np.array([lib, bench, thread, np.mean(result_data).astype(str), np.std(result_data).astype(str)]))
				# print("%s %s %s %.3f %.3f" % (lib, bench, thread, np.mean(result_data), np.std(result_data)))
	avg_result = np.array(avg_result)
	return avg_result, libname, benchname, threadlist

x86filename = sys.argv[1]
armfilename = sys.argv[2]
name = sys.argv[3]
x86data = common.read_data(x86filename)
armdata = common.read_data(armfilename)
x86_avg, x86_libname, x86_benchname, x86_threadlist = avg(x86data)
arm_avg, arm_libname, arm_benchname, arm_threadlist = avg(armdata)

# print(x86_libname)
# print(x86_benchname)
# print(x86_threadlist)
# print(x86_avg)
# print(arm_avg)

# 求加速比


# 画图
def draw_subfig_mop(avg_data, libnames, thread_list, axs, xlabel, ylabel):
	# 获得该bench的数据后,根据lock信息
	xticks = thread_list
	print (xticks)

	i = 0
	for idx in range(0, len(libnames)):
		# 取得数据
		# 原始算法
		lib_avg0 = common.choose(common.choose(avg_data, use_bbench, 1), libnames[idx], 0)
		y0 =  lib_avg0[:, 3].astype(float)
		err0 = lib_avg0[:, 4].astype(float)
		# 新算法
		lib_avg1 = common.choose(common.choose(avg_data, use_abench, 1) , libnames[idx], 0)
		y1 =  lib_avg1[:, 3].astype(float)
		err1 = lib_avg1[:, 4].astype(float)
		#加速比
		y = y1/y0
		print(y)
		axs.plot(xticks, y, color=colors[idx%len(libnames)], fillstyle = fst[idx%len(libnames)], label=libnames[idx], marker=markers[idx%len(libnames)], markersize = 6)
		# 误差棒影响可读性
		# axs.errorbar(xticks, y, yerr = err,  ecolor=colors[i%len(use_libs)], fmt=".k", 
		# marker = " ",
		# alpha = 0.667, elinewidth=1, capsize=2)
	axs.hlines(y=1.0, xmin=0, xmax=len(xticks) - 0.75, linewidth=1, linestyle='--', color = cl_blk)
	axs.set_xticklabels(xticks)
	axs.set_xlabel(xlabel)
	axs.set_ylabel(ylabel)
	axs.set_ylim(0.5, 2.0)
	# axs.set_ylim(0.6)
	# axs.set_yscale("log")
	# 计算本次的差距
	# axs.yaxis.set_major_formatter(ScalarFormatter())
	# axs.yaxis.set_major_formatter(LogFormatter)
	# print (axs.get_ylim())
	# axs.set_yticks([1, 2.5, 5, 7.5, 10, (round(axs.get_ylim()[1], -1) - 10) / 2 + 10, round(axs.get_ylim()[1], -1)] )
	# axs.get_yaxis().get_major_formatter().labelOnlyBase = False
	# axs.set_yticks(np.arange(0, round(axs.get_ylim()[1]), 5))
	# print (caclocks_data, noncaclocks_data)


# # 子图形式绘图

fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(9, 3))
draw_subfig_mop(x86_avg, x86_libname, x86_threadlist, axs[0], txt_thread_nr, txt_mops)
draw_subfig_mop(arm_avg, arm_libname, arm_threadlist, axs[1], txt_thread_nr, "")
plt.legend(loc='upper center', bbox_to_anchor=(-0.10, 1.34), frameon=False, columnspacing=1, handletextpad=0.1, ncol= len(x86_libname)/2 + 1)
matplotlib.pyplot.subplots_adjust(left=0.07, right = 0.995, bottom = 0.15, top = 0.82, wspace = 0.1 )
plt.savefig("./fig/" + name + ".pdf", format = "pdf")
# show
plt.show()